import axios, { type InternalAxiosRequestConfig } from "axios";
import { showFailToast } from "vant";

const instance = axios.create({
  baseURL: "https://meikou-api.itheima.net",
  timeout: 30000,
});

// 请求拦截器
instance.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 注入token-> user里有token
    const user = ljg.getUser();
    if (user.token) {
         config.headers.Authorization = `Bearer ${user.token}`
    } else {
      showFailToast("应用认证失败");
      return Promise.reject(new Error("应用认证失败"));
    }
    return config;
  },
  (error) => Promise.reject(error)
);

// 响应拦截器
instance.interceptors.response.use((response) => {
    return response.data;
  },
  (error) => Promise.reject(error)
);

export class RequestAxios {
  static get<T>(url: string, params?: object) {
    return instance.get<null, T>(url, {
      params,
    });
  }
  static post<T>(url: string, data?: object) {
    return instance.post<null, T>(url, data);
  }
  static put<T>(url: string, data?: object) {
    return instance.put<null, T>(url, data);
  }
  static delete<T>(url: string, params?: object) {
    return instance.delete<null, T>(url, {
      params,
    });
  }
}
